package com.ny.controller;
import com.ny.entity.Result;
import com.ny.entity.Device;
import com.ny.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api") // 添加这个注解，使所有接口都有/api前缀
public class DeviceController {
    @Autowired
    private DeviceService deviceService;

    // 接口：http://localhost:8083/api/findAll

    @GetMapping("/findAll")
    public Result findAll() {
        return Result.success(deviceService.findAll());
    }
    
    // 根据设备名称查询设备信息
    @GetMapping("/findByName")
    public Result findByName(@RequestParam String deviceName) {
        return Result.success(deviceService.findByDeviceName(deviceName));
    }
    
    // 查询指定时间范围内且状态为离线的设备
    @GetMapping("/findByTimeRangeAndOffline")
    public Result findByTimeRangeAndOffline(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime) {
        // 状态0表示离线
        return Result.success(deviceService.findByTimeRangeAndStatus(startTime, endTime, 0));
    }
    
    // 根据设备ID删除设备
    @DeleteMapping("/deleteDevice")
    public Result deleteDevice(@RequestParam Integer deviceId) {
        deviceService.deleteByDeviceId(deviceId);
        return Result.success("设备删除成功");
    }
    
    // 添加设备
    @PostMapping("/addDevice")
    public Result addDevice(@RequestBody Device device) {
        // 设置创建时间
        device.setCreatedTime(new Date());
        // 设置默认状态为在线
        if (device.getStatus() == null) {
            device.setStatus(1);
        }
        deviceService.addDevice(device);
        return Result.success("设备添加成功");
    }
    
    // 编辑设备
    @PutMapping("/updateDevice")
    public Result updateDevice(@RequestBody Device device) {
        deviceService.updateDevice(device);
        return Result.success("设备更新成功");
    }
    
    // 控制设备开关
    @PostMapping("/controlDevice")
    public Result controlDevice(@RequestParam Integer deviceId, @RequestParam Integer status) {
        deviceService.controlDevice(deviceId, status);
        return Result.success("设备控制成功");
    }
    
    // 发送设备控制命令
    @PostMapping("/controlDeviceCommand")
    public Result controlDeviceCommand(@RequestBody Map<String, Object> commandData) {
        // 这里可以处理具体的设备控制命令
        Integer deviceId = (Integer) commandData.get("deviceId");
        String command = (String) commandData.get("command");
        
        // 实际项目中这里会根据设备类型和命令执行具体的控制逻辑
        System.out.println("控制设备 " + deviceId + " 执行命令: " + command);
        
        return Result.success("命令发送成功");
    }
}